<script setup lang="ts">
import CryptoJS from 'crypto-js'
import { local } from '@/utils/storage'
import loginApi from '@/service/api/login'
import { useLoadingBar } from 'naive-ui'
import { useRouter } from 'vue-router'
import { authLogin } from '@/router/index'
import type { FormRules, FormInst } from 'naive-ui'
import type { ILoginParams } from '@/types/api'
import { useTemplateRef } from 'vue'
import { cloneDeep } from 'lodash-es'
import { themesStore } from '@/stores/modules/theme'
defineOptions({
  name: 'LoginPage',
})
const theme = themesStore()
const { getIsDark: isDark } = storeToRefs(theme)

const inutStyle = computed(() => {
  const style = {
    '--n-height': '45px',
  }
  if (!isDark.value) {
    style['--n-color'] = '#e8f1f9'
  }
  return style
})

const queryForm = ref<ILoginParams>({
  randomStr: String(Math.random() * 10),
  username: '',
  code: '',
  password: '',
})
const rules: FormRules = {
  username: [
    {
      required: true,
      message: '账号不能为空',
    },
  ],
  password: [
    {
      required: true,
      message: '密码不能为空',
    },
  ],
  code: [
    {
      required: true,
      message: '验证码不能为空',
    },
  ],
}
const jPass = ref(false)
const handReloadRandom = () => {
  queryForm.value.randomStr = String(Math.random() * 10)
}
const codeImg = computed(() => {
  const baseUrl = import.meta.env.VITE_BASEURL
  return `${baseUrl}/admin/login/captcha?random=${queryForm.value.randomStr}&w=100&h=50`
})

const loginLoading = ref(false)
const formRef = useTemplateRef<FormInst | null>('formRef')
const handLogin = () => {
  formRef.value?.validate((errors) => {
    if (errors && errors.length > 0) {
      const info = errors[0][0]
      msgUtil.$message.error(info.message)
    } else {
      login()
    }
  })
}
const loadingBar = useLoadingBar()
const router = useRouter()
const login = async () => {
  try {
    const params = cloneDeep(queryForm.value)
    const reg = /[\t\r\f\n\s]*/g
    params.username = params.username.replace(reg, '')
    params.password = CryptoJS.MD5(params.password).toString()
    if (loginLoading.value) return
    loginLoading.value = true
    loadingBar.start()
    const { code, data, msg } = await loginApi.login(params)
    if (code !== 0) {
      handReloadRandom()
      loginLoading.value = false
      loadingBar.error()
      msgUtil.$message.error(msg)
      return
    }
    if (jPass.value) {
      local.set('pass', {
        username: params.username,
        password: queryForm.value.password,
      })
    } else {
      local.remove('pass')
    }
    const firthPath = await authLogin(data['token'])
    loadingBar.finish()
    router.replace(firthPath)
  } catch {
    handReloadRandom()
    loginLoading.value = false
    loadingBar.error()
  }
}

onMounted(() => {
  const pass = local.get('pass')
  if (pass) {
    jPass.value = true
    queryForm.value.password = pass.password
    queryForm.value.username = pass.username
  }
})
</script>
<template>
  <div class="loginPage">
    <div class="loginPage-main">
      <div class="img">
        <img src="@/assets/login/cha.png" alt="" />
      </div>
      <div class="form">
        <h2>
          <span>用户</span>
          <span>登录</span>
        </h2>
        <div class="card">
          <n-form ref="formRef" :model="queryForm" show-feedback :rules="rules">
            <n-form-item style="--n-label-height: 0" path="username">
              <n-input
                round
                :style="inutStyle"
                v-model:value="queryForm.username"
                placeholder="请输入用户名"
              >
                <template #prefix>
                  <img class="icon" src="@/assets/login/user.png" />
                </template>
              </n-input>
            </n-form-item>
            <n-form-item style="--n-label-height: 0" path="password">
              <n-input
                round
                type="password"
                :style="inutStyle"
                v-model:value="queryForm.password"
                placeholder="请输入密码"
              >
                <template #prefix>
                  <img class="icon" src="@/assets/login/pass.png" />
                </template>
              </n-input>
            </n-form-item>
            <n-form-item style="--n-label-height: 0" path="code">
              <div class="codes">
                <div class="zdy-input">
                  <n-input
                    round
                    :style="inutStyle"
                    v-model:value="queryForm.code"
                    placeholder="请输入验证码"
                  >
                    <template #prefix>
                      <img class="icon" style="height: 23px" src="@/assets/login/code.png" />
                    </template>
                  </n-input>
                </div>
                <div @click="handReloadRandom">
                  <img class="code-img" :src="codeImg" alt="" />
                </div>
              </div>
            </n-form-item>
          </n-form>
          <n-checkbox v-model:checked="jPass">记住密码</n-checkbox>
          <n-button
            block
            style="--n-height: 45px; --n-border: none; --n-font-size: 15px"
            round
            strong
            class="login-btn"
            :disabled="loginLoading"
            @click="handLogin"
          >
            <n-spin stroke="#fff" v-if="loginLoading">
              <template #icon>
                <i class="esayIcon esayIcon-a-jiazaizhongdaxiao" style="color: #fff"></i>
              </template>
            </n-spin>
            <span>登录</span>
          </n-button>
          <!-- <button @click="toggleDarkMode">切换暗黑模式</button> -->
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.loginPage {
  width: 100%;
  height: 100%;
  position: relative;
  background: url('@/assets/login/bg.png') no-repeat;
  background-size: cover;
  background-position: center;
  background-color: #13151a;

  &-main {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 10% 0 193px;
    box-sizing: border-box;
    .img {
      flex: 1 0 0;
      img {
        width: 100%;
        max-width: 800px;
      }
    }
    .form {
      width: 500px;
      background: var(--yang-login-card-bg-color);
      border-radius: 20px;
      padding: 20px 20px 30px 20px;
      h2 {
        text-align: center;
        letter-spacing: 2px;
        span {
          font-size: 30px;
          color: #1da2ff;
          &:first-child {
            color: #1468ff;
          }
        }
      }
      .icon {
        width: 20px;
        height: 20px;
        margin-left: 10px;
        margin-right: 10px;
      }
      .card {
        margin-top: 40px;
        padding: 0 40px 10px 40px;
        .login-btn {
          margin-top: 30px;
          color: #fff;
          background: linear-gradient(to right, #1603ff, #00a9ff);
        }
      }
      .codes {
        width: 100%;
        display: flex;
        align-items: center;
        .zdy-input {
          flex: 1;
        }
        .code-img {
          margin-left: 20px;
          width: 100px;
          height: 50px;
          cursor: pointer;
        }
      }
    }
  }
}
</style>
